{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #把字符串转换成整数 (atoi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Medium"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #string"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #字符串"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: myAtoi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #把字符串转换成整数 (atoi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>请你来实现一个&nbsp;<code>myAtoi(string s)</code>&nbsp;函数，使其能将字符串转换成一个 32 位有符号整数（类似 C/C++ 中的 <code>atoi</code> 函数）。</p>\n",
    "\n",
    "<p>函数&nbsp;<code>myAtoi(string s)</code> 的算法如下：</p>\n",
    "\n",
    "<ol>\n",
    "\t<li>读入字符串并丢弃无用的前导空格</li>\n",
    "\t<li>检查下一个字符（假设还未到字符末尾）为正还是负号，读取该字符（如果有）。 确定最终结果是负数还是正数。 如果两者都不存在，则假定结果为正。</li>\n",
    "\t<li>读入下一个字符，直到到达下一个非数字字符或到达输入的结尾。字符串的其余部分将被忽略。</li>\n",
    "\t<li>将前面步骤读入的这些数字转换为整数（即，\"123\" -&gt; 123， \"0032\" -&gt; 32）。如果没有读入数字，则整数为 <code>0</code> 。必要时更改符号（从步骤 2 开始）。</li>\n",
    "\t<li>如果整数数超过 32 位有符号整数范围 <code>[−2<sup>31</sup>,&nbsp; 2<sup>31&nbsp;</sup>− 1]</code> ，需要截断这个整数，使其保持在这个范围内。具体来说，小于 <code>−2<sup>31</sup></code> 的整数应该被固定为 <code>−2<sup>31</sup></code> ，大于 <code>2<sup>31&nbsp;</sup>− 1</code> 的整数应该被固定为 <code>2<sup>31&nbsp;</sup>− 1</code> 。</li>\n",
    "\t<li>返回整数作为最终结果。</li>\n",
    "</ol>\n",
    "\n",
    "<p><strong>注意：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li>本题中的空白字符只包括空格字符 <code>' '</code> 。</li>\n",
    "\t<li>除前导空格或数字后的其余字符串外，<strong>请勿忽略</strong> 任何其他字符。</li>\n",
    "</ul>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>示例&nbsp;1：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>s = \"42\"\n",
    "<strong>输出：</strong>42\n",
    "<strong>解释：</strong>加粗的字符串为已经读入的字符，插入符号是当前读取的字符。\n",
    "第 1 步：\"42\"（当前没有读入字符，因为没有前导空格）\n",
    "         ^\n",
    "第 2 步：\"42\"（当前没有读入字符，因为这里不存在 '-' 或者 '+'）\n",
    "         ^\n",
    "第 3 步：\"<u>42</u>\"（读入 \"42\"）\n",
    "           ^\n",
    "解析得到整数 42 。\n",
    "由于 \"42\" 在范围 [-2<sup>31</sup>, 2<sup>31</sup> - 1] 内，最终结果为 42 。</pre>\n",
    "\n",
    "<p><strong>示例&nbsp;2：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>s = \"   -42\"\n",
    "<strong>输出：</strong>-42\n",
    "<strong>解释：</strong>\n",
    "第 1 步：\"<u><strong>   </strong></u>-42\"（读入前导空格，但忽视掉）\n",
    "            ^\n",
    "第 2 步：\"   <u><strong>-</strong></u>42\"（读入 '-' 字符，所以结果应该是负数）\n",
    "             ^\n",
    "第 3 步：\"   <u><strong>-42</strong></u>\"（读入 \"42\"）\n",
    "               ^\n",
    "解析得到整数 -42 。\n",
    "由于 \"-42\" 在范围 [-2<sup>31</sup>, 2<sup>31</sup> - 1] 内，最终结果为 -42 。\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例&nbsp;3：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>s = \"4193 with words\"\n",
    "<strong>输出：</strong>4193\n",
    "<strong>解释：</strong>\n",
    "第 1 步：\"4193 with words\"（当前没有读入字符，因为没有前导空格）\n",
    "         ^\n",
    "第 2 步：\"4193 with words\"（当前没有读入字符，因为这里不存在 '-' 或者 '+'）\n",
    "         ^\n",
    "第 3 步：\"<u>4193</u> with words\"（读入 \"4193\"；由于下一个字符不是一个数字，所以读入停止）\n",
    "             ^\n",
    "解析得到整数 4193 。\n",
    "由于 \"4193\" 在范围 [-2<sup>31</sup>, 2<sup>31</sup> - 1] 内，最终结果为 4193 。\n",
    "</pre>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>提示：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>0 &lt;= s.length &lt;= 200</code></li>\n",
    "\t<li><code>s</code> 由英文字母（大写和小写）、数字（<code>0-9</code>）、<code>' '</code>、<code>'+'</code>、<code>'-'</code> 和 <code>'.'</code> 组成</li>\n",
    "</ul>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p>注意：本题与主站 8 题相同：<a href=\"https://leetcode-cn.com/problems/string-to-integer-atoi/\">https://leetcode-cn.com/problems/string-to-integer-atoi/</a></p>\n",
    "\n",
    "<p>&nbsp;</p>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof](https://leetcode.cn/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof](https://leetcode.cn/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = []"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        ans = 0 \n",
    "        s = s.strip()\n",
    "        if not s:\n",
    "            return 0\n",
    "\n",
    "        flag = 1\n",
    "        if s[0] in ['-', '+']:\n",
    "            flag = -1 if s[0] == '-' else 1\n",
    "            s = s[1:]\n",
    "        elif not '0' <= s[0] <= '9':\n",
    "            return 0\n",
    "\n",
    "        INT_MAX = 2**31 - 1\n",
    "        INT_MIN = - 2**31\n",
    "        for i, c in enumerate(s):\n",
    "            if '0' <= c <= '9':\n",
    "                ans = ans * 10 + ord(c) - ord('0')\n",
    "                if ans > INT_MAX:\n",
    "                    break\n",
    "            else:\n",
    "                break\n",
    "        ans = ans * flag\n",
    "        if ans > INT_MAX:\n",
    "            return INT_MAX\n",
    "        elif ans < INT_MIN:\n",
    "            return INT_MIN\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        s = str.lstrip()\n",
    "        if len(s) == 0:\n",
    "            return 0\n",
    "        data = []\n",
    "        p_n = 1\n",
    "        if s[0] == '+':\n",
    "            p_n = 1\n",
    "        elif s[0] == '-':\n",
    "            p_n = 0\n",
    "        else:\n",
    "            if s[0].isdigit():\n",
    "                data.append(int(s[0]))\n",
    "            else:\n",
    "                return 0\n",
    "        for i in range(1, len(s)):\n",
    "            if s[i].isdigit():\n",
    "                data.append(int(s[i]))\n",
    "            else:\n",
    "                break\n",
    "        length = len(data)\n",
    "        if length == 0:\n",
    "            return 0\n",
    "        else:\n",
    "            sum_num = 0\n",
    "            for i in range(length):\n",
    "                sum_num = sum_num + data[i] * (10 ** (length - (i + 1)))\n",
    "        if p_n == 1:\n",
    "            if sum_num <= 2 ** 31 -1:\n",
    "                return sum_num\n",
    "            else:\n",
    "                return 2 ** 31 -1\n",
    "        else:\n",
    "            if sum_num <= 2 ** 31:\n",
    "                return -sum_num\n",
    "            else:\n",
    "                return -2 ** 31\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()\n",
    "        i, intMax, intmin, sign, bndry, res = 1, 2**31-1, -2**31, 1, 2**31 // 10, 0\n",
    "        if not str: return 0\n",
    "        if str[0] == '-': sign = -1\n",
    "        elif str[0] != '+': i = 0\n",
    "        for c in str[i:]:\n",
    "            if c < '0' or c > '9': break            \n",
    "            if res > bndry or res == bndry and c > '7': return intMax if sign == 1 else intmin\n",
    "            res = res * 10 + ord(c) - ord('0')\n",
    "        return res * sign"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        s = str\n",
    "        n = len(s)\n",
    "        if not n:\n",
    "            return 0\n",
    "        int_max, int_min = 2**31-1, -2**31\n",
    "        bound = int_max // 10\n",
    "        sign = 1\n",
    "        res = 0\n",
    "        for i in range(n):\n",
    "            if s[i] == \" \":\n",
    "                continue\n",
    "            if s[i] == \"+\":\n",
    "                i += 1\n",
    "            elif s[i] == \"-\":\n",
    "                i += 1\n",
    "                sign = -1\n",
    "            while i < n and \"0\"<=s[i]<=\"9\":\n",
    "                if res > bound or (res == bound and s[i]>\"7\"):\n",
    "                    if sign == 1:\n",
    "                        return int_max\n",
    "                    elif sign == -1:\n",
    "                        return int_min\n",
    "                res = res * 10 + int(s[i])\n",
    "                i += 1\n",
    "            return res * sign\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        return max(min(int(*re.findall(\"^[\\+\\-]?\\d+\", str.lstrip())), 2**31-1), -2**31)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        s = str\n",
    "        sign = 1\n",
    "        n = len(s)\n",
    "        max_int, min_int = 2**31-1, -2**31\n",
    "        bound = max_int // 10\n",
    "        res = 0\n",
    "        for i in range(n):\n",
    "            if s[i] == \" \":\n",
    "                continue\n",
    "            if s[i] == \"+\":\n",
    "                i += 1\n",
    "            elif s[i] == \"-\":\n",
    "                sign = -1\n",
    "                i += 1\n",
    "            while i < n and \"0\"<=s[i]<=\"9\":\n",
    "                if res > bound or (res==bound and s[i] > \"7\"):\n",
    "                    if sign == 1:\n",
    "                        return max_int\n",
    "                    if sign == -1:\n",
    "                        return min_int\n",
    "                res = res * 10 + int(s[i])\n",
    "                i += 1\n",
    "            return res * sign\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        # 丢弃无用的前导空格\n",
    "        str = str.lstrip()\n",
    "        if not str:\n",
    "            return 0\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        # 获取符号\n",
    "        if str[0] == '-':\n",
    "            sign = -1\n",
    "        elif str[0] != '+':\n",
    "            i = 0\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9':\n",
    "                break\n",
    "            if res > bndry or res == bndry and c > '7':\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = 10 * res + ord(c) - ord('0')\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        '''\n",
    "        #思路：遍历字符串，有下面几种情况需要考虑：\n",
    "        1）空格：跳过；\n",
    "        2）正负号：定义一个变量，记录正负，最终返回结果前加上判断正负；\n",
    "        3）判断是否时数字，如果是，则字符转换为数字，用字符的ascii码减去'0'的ascii码，然后判断加上当前数之后（原res*10+当前位数字）的结果是否在32位内，\n",
    "        在则加上，超过则直接返回临界值\n",
    "        4）不是数字，直接返回\n",
    "        :param str:\n",
    "        :return:\n",
    "        '''\n",
    "        if not str:\n",
    "            return 0\n",
    "        i,res = 0,0\n",
    "        flag = True\n",
    "        # 空格\n",
    "        while i < len(str) and str[i] == ' ':\n",
    "            i += 1\n",
    "        #都是空格\n",
    "        if i == len(str):\n",
    "            return 0\n",
    "        #正负号\n",
    "        if str[i] in ('-','+'):\n",
    "            if str[i] == '-':\n",
    "                flag = False\n",
    "            i += 1\n",
    "        #判断是否是数字\n",
    "        while i < len(str) and str[i] >= '0' and str[i] <= '9':\n",
    "            tmp = ord(str[i]) - ord('0')\n",
    "            #判断是否溢出\n",
    "            if flag and (res * 10 + tmp) > 2147483647:\n",
    "                return 2147483647\n",
    "            elif not flag and -(res * 10 + tmp) < -2147483648:\n",
    "                return -2147483648\n",
    "            else:\n",
    "                res = res * 10 + tmp\n",
    "            i += 1\n",
    "\n",
    "        return res if flag else -res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        res,i,sign,length = 0, 0, 1, len(str)\n",
    "        int_max, int_min, bnd = 2**31-1, -2**31, 2**31//10\n",
    "        while i<length and str[i]==' ':\n",
    "            i+=1\n",
    "        if i==len(str):\n",
    "            return 0\n",
    "        if str[i]=='-':\n",
    "            sign=-1\n",
    "        if str[i] in '-+':\n",
    "            i+=1\n",
    "        while i<len(str):\n",
    "            if not '0'<=str[i]<='9':\n",
    "                break\n",
    "            if res==bnd and str[i]>'7' or res>bnd:\n",
    "                return int_min if sign<0 else int_max\n",
    "            res = res*10+int(str[i])\n",
    "            i+=1\n",
    "        return sign*res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        s = s.strip()             # 删除左右空字符\n",
    "        if not s: \n",
    "            return 0     # 判空\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_min, int_max, bndry = - 2 ** 31, 2 ** 31 - 1, 2 ** 31 // 10\n",
    "        if s[0] == '-': \n",
    "            sign = -1\n",
    "        elif s[0] != '+': \n",
    "            i = 0\n",
    "        for c in s[i:]:\n",
    "            if  not '0' <= c <= '9': \n",
    "                break                       # 遇到非数字字符直接跳出\n",
    "            if res > bndry or res == bndry and c > '7':\n",
    "                return int_min if sign == -1 else int_max\n",
    "            res = res*10 + ord(c) - ord('0')\n",
    "        return res * sign\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        if not str:\n",
    "            return 0\n",
    "        int_max, int_min, bndry = 2**31 - 1, -2**31,  2**31//10\n",
    "        res, i,  length, sign = 0, 0, len(str), 1\n",
    "        while str[i] == ' ':\n",
    "            i += 1\n",
    "            if i == length:\n",
    "                return 0\n",
    "        if str[i] == '-':\n",
    "            sign = -1\n",
    "        if str[i] in '+-':\n",
    "            i += 1\n",
    "        for j in range(i, length):\n",
    "            if str[j] < '0' or str[j] > '9':\n",
    "                break\n",
    "            if res > bndry or res == bndry and str[j] > '7':\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = res * 10 + (ord(str[j]) - ord('0'))\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        # 1\n",
    "        s = str.strip()\n",
    "        res = 0\n",
    "        if len(s) == 0:\n",
    "            return 0\n",
    "        sign_flag = 1\n",
    "        if s[0] in \"+-\":\n",
    "            if s[0] == \"-\":\n",
    "                sign_flag = -1\n",
    "            s = s[1:]\n",
    "        for item in s:\n",
    "            if item >= \"0\" and item <= \"9\":\n",
    "                res = res*10+int(item)\n",
    "            else:\n",
    "                break\n",
    "        res = sign_flag * res\n",
    "        return max(\n",
    "            min(res, 2**31-1),\n",
    "            -2**31\n",
    "        )\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        res, i, sign, length = 0, 0, 1, len(str)\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if not str: return 0         # 空字符串，提前返回\n",
    "        while str[i] == ' ':\n",
    "            i += 1\n",
    "            if i == length: return 0 # 字符串全为空格，提前返回\n",
    "        if str[i] == '-': sign = -1\n",
    "        if str[i] in '+-': i += 1\n",
    "        for j in range(i, length):\n",
    "            if not '0' <= str[j] <= '9' : break\n",
    "            if res > bndry or res == bndry and str[j] > '7':\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = 10 * res + ord(str[j]) - ord('0')\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()\n",
    "        if not str: return 0\n",
    "        res, i , sign = 0,1,1\n",
    "        int_max,int_min,bndry = 2 ** 31-1,-2 ** 31,2 ** 31 // 10\n",
    "        if str[0] == '-': sign =-1\n",
    "        elif str[0] != '+': i = 0\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9':break\n",
    "            if res > bndry or res == bndry and c > '7':return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        res, i, sign, length = 0, 0, 1, len(str)\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if not str: return 0         # 空字符串，提前返回\n",
    "        while str[i] == ' ':\n",
    "            i += 1\n",
    "            if i == length: return 0 # 字符串全为空格，提前返回\n",
    "        if str[i] == '-': sign = -1\n",
    "        if str[i] in '+-': i += 1\n",
    "        for j in range(i, length):\n",
    "            if not '0' <= str[j] <= '9' : break\n",
    "            if res > bndry or res == bndry and str[j] > '7':\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = 10 * res + ord(str[j]) - ord('0')\n",
    "        return sign * res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        res=''\n",
    "        x=0\n",
    "        for i in str:\n",
    "            if '0'<=i<='9':\n",
    "                res+=i\n",
    "            else:\n",
    "                if x==0 and not res:\n",
    "                    if i==' ':\n",
    "                        continue\n",
    "                    elif i=='-':\n",
    "                        x=1\n",
    "                    elif i=='+':\n",
    "                        x=-1\n",
    "                    else:\n",
    "                        break\n",
    "                else:\n",
    "                    break\n",
    "        if not res:\n",
    "            return 0\n",
    "        if x==0 or x==-1:\n",
    "            res=int(res)\n",
    "        else:\n",
    "            res=-int(res)\n",
    "        if res>=2**31-1:\n",
    "            return 2**31-1\n",
    "        elif res<=-2**31:\n",
    "            return -2**31\n",
    "        else:\n",
    "            return res\n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()\n",
    "        if not str:\n",
    "            return 0\n",
    "        ans = 0\n",
    "        sign = 1\n",
    "        i = 1\n",
    "        if str[0] == \"-\":\n",
    "            sign = -1\n",
    "        elif str[0] != \"+\":\n",
    "            i = 0\n",
    "        for i in range(i, len(str)):\n",
    "            if not '0' <= str[i] <= '9':\n",
    "                break\n",
    "            ans = 10 * ans + ord(str[i]) - ord('0')\n",
    "            if ans > 2 ** 31 - 1 :\n",
    "                ans = 2 ** 31 \n",
    "                flag = 1\n",
    "                break\n",
    "        if sign == -1 :\n",
    "            return ans * sign\n",
    "        if sign == 1:\n",
    "            if ans == 2 ** 31:\n",
    "                return ans - 1\n",
    "            else:\n",
    "                return ans * sign\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()\n",
    "        if not str:\n",
    "            return 0\n",
    "        ans = ''\n",
    "        if str[0] == '-':\n",
    "            ans = '-'\n",
    "        i = 1 if str[0] == '+' or str[0] == '-' else 0\n",
    "        while i < len(str):\n",
    "            if '0' <= str[i] <= '9':\n",
    "                ans += str[i]\n",
    "            else:\n",
    "                break\n",
    "            i += 1\n",
    "        if not ans or ans == '-':\n",
    "            return 0\n",
    "        ans = int(ans)\n",
    "        if ans < -2**31:\n",
    "            ans = -2**31\n",
    "        elif ans > 2**31 - 1:\n",
    "            ans = 2**31 - 1\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        mydict = {\"0\": 0, \"1\": 1, \"2\": 2, \"3\": 3, \"4\": 4,\n",
    "                  \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9}\n",
    "        flag, i = 0, 0\n",
    "        ans = 0\n",
    "        while i < len(s) and s[i] == \" \":\n",
    "            i += 1\n",
    "        if i == len(s):\n",
    "            return ans\n",
    "        if s[i] == \"+\":\n",
    "            i += 1\n",
    "        elif s[i] == \"-\":\n",
    "            flag = -1\n",
    "            i += 1\n",
    "\n",
    "        while i < len(s):\n",
    "            if s[i] not in mydict:\n",
    "                break\n",
    "            else:\n",
    "                ans = ans * 10 + mydict[s[i]]\n",
    "                if flag == -1 and ans > pow(2, 31):\n",
    "                    return int(-pow(2, 31))\n",
    "                elif flag != -1 and ans > pow(2, 31) - 1:\n",
    "                    return int(pow(2, 31) - 1)\n",
    "            i += 1\n",
    "        if flag == -1:\n",
    "            ans = 0-ans\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        int_max,int_min,bndary = 2**31-1,-2**31,2**31//10\n",
    "        sign,i,res = 1,0,0\n",
    "        if not str:\n",
    "            return 0\n",
    "        while str[i]==' ':\n",
    "            i+=1\n",
    "            if i == len(str): return 0\n",
    "        if str[i] == '-':\n",
    "            sign = -1\n",
    "        if str[i] == '+' or str[i]=='-':\n",
    "            i+=1\n",
    "        for j in range(i,len(str)):\n",
    "            if str[j]<'0' or str[j]>'9':\n",
    "                break\n",
    "            if res > bndary or (res == bndary and str[j]>'7'):\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = 10*res + ord(str[j]) - ord('0')\n",
    "        return sign*res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        s = s.strip()                      # 删除首尾空格\n",
    "        if not s: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if s[0] == '-': sign = -1            # 保存负号\n",
    "        elif s[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in s[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        res, i, sign, length = 0, 0, 1, len(str)\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if not str: return 0         # 空字符串，提前返回\n",
    "        while str[i] == ' ':\n",
    "            i += 1\n",
    "            if i == length: return 0 # 字符串全为空格，提前返回\n",
    "        if str[i] == '-': sign = -1\n",
    "        if str[i] in '+-': i += 1\n",
    "        for j in range(i, length):\n",
    "            if not '0' <= str[j] <= '9' : break\n",
    "            if res > bndry or res == bndry and str[j] > '7':\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = 10 * res + ord(str[j]) - ord('0')\n",
    "        return sign * res\n",
    "\n",
    "         "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        s = s.lstrip(' ')\n",
    "        num = 0\n",
    "        sign = 1\n",
    "        hasNum = hasSign = False\n",
    "        for c in s:\n",
    "            if c in '+-' and not hasSign and not hasNum:\n",
    "                hasSign = True\n",
    "                if c == '-': sign = -1\n",
    "            elif c.isdigit():\n",
    "                hasNum = True\n",
    "                num = num * 10 + ord(c) - ord('0')\n",
    "                if sign < 0 and num > 1 << 31: return - (1 << 31)\n",
    "                if sign > 0 and num > (1 << 31) - 1: return (1 << 31) - 1\n",
    "            elif hasNum:\n",
    "                break\n",
    "            else:\n",
    "                return 0\n",
    "\n",
    "        return sign * num"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()\n",
    "        if len(str) == 0:\n",
    "            return 0\n",
    "        res, sign, i = 0, 1, 0\n",
    "        if str[0] == '-':\n",
    "            sign = - sign\n",
    "        if str[0] in ['-', '+']:\n",
    "            str = str[1:]\n",
    "        while i < len(str) and str[i].isdigit():\n",
    "            res = res * 10 + int(str[i])\n",
    "            i += 1\n",
    "        res = res * sign\n",
    "        if res < -2**31:\n",
    "            return -2**31\n",
    "        if res > 2**31 - 1:\n",
    "            return 2**31 - 1\n",
    "        return res \n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        res, i, sign, length = 0, 0, 1, len(str)\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if not str: return 0         # 空字符串，提前返回\n",
    "        while str[i] == ' ':\n",
    "            i += 1\n",
    "            if i == length: return 0 # 字符串全为空格，提前返回\n",
    "        if str[i] == '-': sign = -1\n",
    "        if str[i] in '+-': i += 1\n",
    "        for j in range(i, length):\n",
    "            if not '0' <= str[j] <= '9' : break\n",
    "            if res > bndry or res == bndry and str[j] > '7':\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = 10 * res + ord(str[j]) - ord('0')\n",
    "        return sign * res\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()\n",
    "        temp = ''\n",
    "        flag = ''\n",
    "        res = 0\n",
    "        for i in range(len(str)):\n",
    "            if i == 0 and str[i] != '-' and str[i] != '+':\n",
    "                if not str[i].isdigit():\n",
    "                    break\n",
    "            if i == 0 and str[i] == '-' or  i == 0 and str[i] == '+':\n",
    "                flag += str[i]\n",
    "            elif str[i].isdigit():\n",
    "                if str[i] == '.':\n",
    "                    isDot = True\n",
    "                temp += str[i]\n",
    "            else:\n",
    "                break\n",
    "        if temp == '':\n",
    "            return 0\n",
    "        res =  int(flag + temp)\n",
    "        if res < -2**31:\n",
    "            res = -2147483648\n",
    "        elif res >= 2**31:\n",
    "            res = (2**31-1)\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        # 删除多余空格\n",
    "        str = str.strip()\n",
    "        \n",
    "        if not str:\n",
    "            return 0\n",
    "        \n",
    "        # 定义变量\n",
    "        res = 0     # 结果存储变量\n",
    "        bgn = 1     # 开始位置\n",
    "        sign = 1    # 符号位\n",
    "        \n",
    "        INT_MAX = 2 ** 31 - 1   # 上界\n",
    "        INT_MIN = - 2 ** 31     # 下界\n",
    "        BOUNDARY = INT_MAX // 10 # 边界\n",
    "        \n",
    "        # 若第一位是符号位且为负号\n",
    "        if str[0] == '-':\n",
    "            sign = -1\n",
    "        \n",
    "        # 若第一位不是符号位，则默认为正数\n",
    "        # 开始位置改为0\n",
    "        elif str[0] != '+':\n",
    "            bgn = 0\n",
    "        \n",
    "        for c in str[bgn:]:\n",
    "            # 如果出现非数字字符，跳出循环\n",
    "            if not '0' <= c <= '9':\n",
    "                break\n",
    "            \n",
    "            # 判断越界情况\n",
    "            if res > BOUNDARY or res == BOUNDARY and c > '7':\n",
    "                return INT_MAX if sign == 1 else INT_MIN\n",
    "            \n",
    "            # 执行转换\n",
    "            res = res * 10 + ord(c) - ord('0')\n",
    "        \n",
    "        return sign * res\n",
    "            \n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        INT_MAX, INT_MIN = 2 ** 31 - 1, -2 ** 31\n",
    "        res = 0\n",
    "        sig, start = 1, 0\n",
    "        str = str.strip()\n",
    "        if not str:\n",
    "            return 0\n",
    "        if str[0] in (\"+\", \"-\"):\n",
    "            sig = 1 if str[0] == \"+\" else -1\n",
    "            start = 1\n",
    "        for ele in str[start:]:\n",
    "            if \"0\" <= ele <= \"9\":\n",
    "                x = ord(ele) - ord(\"0\")\n",
    "                if sig == 1 and res >= (INT_MAX - x) / 10:\n",
    "                    return INT_MAX\n",
    "                if sig == -1 and res >= (-1*INT_MIN - x) / 10:\n",
    "                    return INT_MIN\n",
    "                res = res * 10 + x\n",
    "            else:\n",
    "                break\n",
    "        return res * sig  # 注意这一行的位置，如果放在上面else后则在输入为纯数字时永远不会return出值\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, target_str: str) -> int:\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31\n",
    "        ans = 0\n",
    "        negative = False\n",
    "        allow_set = set()\n",
    "        for i in range(10):\n",
    "            allow_set.add(str(i))\n",
    "\n",
    "        i = 0\n",
    "        if not target_str:\n",
    "            return 0\n",
    "        while target_str[i] == ' ':\n",
    "            i += 1\n",
    "            if i == len(target_str):\n",
    "                return 0\n",
    "        if target_str[i] == '-':\n",
    "            negative = True\n",
    "        if target_str[i] in '+-':\n",
    "            i += 1\n",
    "\n",
    "        for j in range(i, len(target_str)):\n",
    "            c = target_str[j]\n",
    "            if not '0' <= c <= '9':\n",
    "                break\n",
    "            ans = (ans * 10 + (ord(c) - ord('0')))\n",
    "        if ans >= bndry:\n",
    "            return int_max if not negative else int_min\n",
    "        else:\n",
    "            return ans if not negative else -ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        i = 0\n",
    "        while i < len(str) and str[i] == \" \":\n",
    "            i += 1\n",
    "\n",
    "        sign = 1\n",
    "        if i < len(str) and (str[i] == \"+\" or str[i] == \"-\"):\n",
    "            if str[i] == \"-\":\n",
    "                sign = -1\n",
    "            i += 1\n",
    "        result = 0\n",
    "\n",
    "        while i < len(str) and str[i].isdigit():\n",
    "            result = result * 10 + int(str[i])\n",
    "            i += 1\n",
    "\n",
    "        result *= sign\n",
    "        if result < (-2 ** 31):\n",
    "            result = -2 ** 31\n",
    "        elif result > 2 ** 31 - 1:\n",
    "            result = 2 ** 31 - 1\n",
    "\n",
    "        return result\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "         #numdic = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}\n",
    "        i = 0\n",
    "        digits=('0','1','2','3','4','5','6','7','8','9')\n",
    "        # 跳过前面的空白\n",
    "        while i < len(str) and str[i] == ' ':\n",
    "            i += 1\n",
    "        # 判断异常转换情况\n",
    "        if i >= len(str) or (str[i] not in digits and str[i] not in ('+','-')):\n",
    "            return 0\n",
    "        # 判断正负性\n",
    "        sign = 1\n",
    "        if str[i] == '-':\n",
    "            sign = -1\n",
    "            i += 1\n",
    "        elif str[i] == '+':\n",
    "            i += 1\n",
    "        # 提取数\n",
    "        num = 0\n",
    "        boundry = 2**31-1 if sign > 0 else 2**31\n",
    "        # 注意先判断索引，以防越界\n",
    "        while i < len(str) and str[i] in digits:\n",
    "            num = num *10 + int(str[i])\n",
    "            i += 1\n",
    "            if num > boundry:\n",
    "                return sign * boundry\n",
    "        return sign * num"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()\n",
    "        if len(str) == 0:return 0\n",
    "        res, i, sign, m = 0, 1, 1, 0\n",
    "        int_max, int_min= 2**31-1, -2**31\n",
    "        if str[0] == \"-\":sign = -1\n",
    "        elif str[0] != \"+\":i = 0\n",
    "        for j in str[i:]:\n",
    "            if not '0'<= j <='9':break\n",
    "            res = 10*res + ord(j) - ord('0')\n",
    "            m = res*sign\n",
    "        if m > int_max:return int_max\n",
    "        elif m < int_min:return int_min\n",
    "        else:return m "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()\n",
    "        if not str:\n",
    "            return 0\n",
    "        sign = 1\n",
    "        bgn = 1\n",
    "        res = 0\n",
    "        INT_MAX = 2 ** 31 -1\n",
    "        INT_MIN = - 2 ** 31\n",
    "        BOUNDRY = INT_MAX // 10\n",
    "        \n",
    "        if str[0] == '-':\n",
    "            sign = -1\n",
    "        elif str[0] != '+':\n",
    "            bgn = 0\n",
    "        \n",
    "        for c in str[bgn:]:\n",
    "            if not '0' <= c <= '9':\n",
    "                break\n",
    "\n",
    "            if res > BOUNDRY or res == BOUNDRY and c > '7':\n",
    "                return INT_MAX if sign == 1 else INT_MIN\n",
    "            \n",
    "            res = res * 10 + ord(c) - ord('0')\n",
    "            \n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()\n",
    "        if not str: return 0\n",
    "        sign, res = 1, 0\n",
    "        max_bdry, min_bdry, bdry = 2**31 - 1, -2**31, 2**31 // 10\n",
    "        if str[0] == '-':\n",
    "            sign = -1\n",
    "            str = str[1:]\n",
    "        elif str[0] == '+':\n",
    "            str = str[1:]\n",
    "        for i in str:\n",
    "            if '0' <= i <= '9': \n",
    "                num = ord(i) - ord('0')\n",
    "            elif i < '0' or i > '9':\n",
    "                break           \n",
    "            if res > bdry or res == bdry and num > 7:\n",
    "                return min_bdry if sign == -1 else max_bdry\n",
    "            res = 10 * res + num\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        i, sign = 0, 1\n",
    "        str = str.strip()\n",
    "        if not str: return 0\n",
    "        if str[0] in ['-', '+']:\n",
    "            sign = -1 if str[0] == '-' else 1\n",
    "            i += 1\n",
    "        l, r = i, i\n",
    "        while r < len(str) and str[r].isdigit(): r += 1\n",
    "        if not str[l:r].isdigit(): return 0\n",
    "        num, int_max = sign * int(str[l:r]), 2 ** 31\n",
    "        return  num if -int_max <= num <= int_max - 1 else -int_max if sign < 0 else int_max - 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()\n",
    "        # 如果字符串为空，则返回\n",
    "        if not str:\n",
    "            return 0\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, binary = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == \"-\":\n",
    "            sign = -1\n",
    "        elif str[0] != \"+\": i = 0\n",
    "        for c in str[i:]:\n",
    "            if not \"0\" <= c <= '9':\n",
    "                break\n",
    "            if res > binary or res == binary and c > \"7\":\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = 10 * res + ord(c) - ord(\"0\")\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        # 1\n",
    "        s = str.strip()\n",
    "        res = 0\n",
    "        if len(s) == 0:\n",
    "            return 0\n",
    "        sign_flag = 1\n",
    "        if s[0] in \"+-\":\n",
    "            if s[0] == \"-\":\n",
    "                sign_flag = -1\n",
    "            s = s[1:]\n",
    "        for item in s:\n",
    "            if item >= \"0\" and item <= \"9\":\n",
    "                res = res*10+int(item)\n",
    "            else:\n",
    "                break\n",
    "        res = sign_flag * res\n",
    "        return max(\n",
    "            min(res, 2**31-1),\n",
    "            -2**31\n",
    "        )\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()\n",
    "        if not str: return 0\n",
    "        sign, res = 1, 0\n",
    "        max_bdry, min_bdry, bdry = 2**31 - 1, -2**31, 2**31 // 10\n",
    "        if str[0] == '-':\n",
    "            sign = -1\n",
    "            str = str[1:]\n",
    "        elif str[0] == '+':\n",
    "            str = str[1:]\n",
    "        for i in str:\n",
    "            if '0' <= i <= '9': \n",
    "                num = ord(i) - ord('0')\n",
    "            elif i < '0' or i > '9':\n",
    "                break           \n",
    "            if res > bdry or res == bdry and num > 7:\n",
    "                return min_bdry if sign == -1 else max_bdry\n",
    "            res = 10 * res + num\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        ans=0\n",
    "        i=0\n",
    "        sign=1\n",
    "        intMax=2**31-1\n",
    "        intMin=-2**31\n",
    "        boundary=2**31//10\n",
    "        if not str:\n",
    "            return 0\n",
    "        while str[i]==\" \":\n",
    "            i+=1\n",
    "            if i==len(str):\n",
    "                return 0\n",
    "        if str[i]==\"-\":\n",
    "            sign=-1\n",
    "        if str[i] in \"+-\":\n",
    "            i+=1\n",
    "        for j in range(i,len(str)):\n",
    "            if not (str[j]>=\"0\" and str[j]<=\"9\"):\n",
    "                break\n",
    "            if ans>boundary or (ans==boundary and str[j]>\"7\"):\n",
    "                return intMax if sign==1 else intMin\n",
    "            ans=ans*10+ord(str[j])-ord(\"0\")\n",
    "        return sign*ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        flag=result=0\n",
    "        p=1\n",
    "        for i in str:\n",
    "            if '0'<=i<='9':\n",
    "                flag=1\n",
    "                result=result*10+int(i)*p\n",
    "            elif i=='-':\n",
    "                if flag:\n",
    "                    break\n",
    "                flag=1\n",
    "                p*=-1\n",
    "            elif i=='+':\n",
    "                if flag:\n",
    "                    break\n",
    "                flag=1\n",
    "            elif flag and i==' ' or i!=' ':\n",
    "                break\n",
    "        if result>2**31-1:\n",
    "            result=2**31-1\n",
    "        elif result<-2**31:\n",
    "            result=-2**31\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# class Solution:\n",
    "#     def myAtoi(self, str: str) -> int:\n",
    "#         int_max,int_min,bndary = 2**31-1,-2**31,2**31//10\n",
    "#         sign,i,res = 1,0,0\n",
    "#         if not str:\n",
    "#             return 0\n",
    "#         while str[i]==' ':\n",
    "#             i+=1\n",
    "#             if i == len(str): return 0\n",
    "#         if str[i] == '-':\n",
    "#             sign = -1\n",
    "#             i+=1\n",
    "#         if str[i] == '+':\n",
    "#             i+=1\n",
    "#         for j in range(i,len(str)):\n",
    "#             if str[j]<'0' or str[j]>'9':\n",
    "#                 break\n",
    "#             if res > bndary or (res == bndary and str[j]>'7'):\n",
    "#                 return int_max if sign == 1 else int_min\n",
    "#             res = 10*res + ord(str[j]) - ord('0')\n",
    "#         return sign*res\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        res, i, sign, length = 0, 0, 1, len(str)\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if not str: return 0         # 空字符串，提前返回\n",
    "        while str[i] == ' ':\n",
    "            i += 1\n",
    "            if i == length: return 0 # 字符串全为空格，提前返回\n",
    "        if str[i] == '-': sign = -1\n",
    "        if str[i] in '+-': i += 1\n",
    "        for j in range(i, length):\n",
    "            if not '0' <= str[j] <= '9' : break\n",
    "            if res > bndry or res == bndry and str[j] > '7':\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = 10 * res + ord(str[j]) - ord('0')\n",
    "        return sign * res\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        flag,nums,sum = 0,[],0\n",
    "\n",
    "        for c in str:\n",
    "            if flag == 0 and c == ' ':\n",
    "                continue\n",
    "\n",
    "            if flag == 0:\n",
    "                if c == '-':\n",
    "                    flag = -1\n",
    "                elif c == '+' or c.isdigit():\n",
    "                    flag = 1\n",
    "                    if c.isdigit():nums.append(int(c))\n",
    "                else:\n",
    "                    break\n",
    "            else:\n",
    "                if not c.isdigit():\n",
    "                    break\n",
    "                else:\n",
    "                    nums.append(int(c))\n",
    "\n",
    "        l = len(nums)\n",
    "        for i in range(l):\n",
    "            sum += nums[i] * pow(10,l-1-i)\n",
    "\n",
    "        sum *= flag\n",
    "        if sum < pow(2,31) * -1:sum = -1 * pow(2,31)\n",
    "        if sum > pow(2,31) - 1:sum = pow(2,31) - 1\n",
    "\n",
    "        return sum\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        s = str.strip()\n",
    "\n",
    "        if len(s) == 0:\n",
    "            return 0\n",
    "        res = 0\n",
    "\n",
    "        sign_flag = 1\n",
    "        if s[0] == \"+\":\n",
    "            s = s[1:]\n",
    "        elif s[0] == \"-\":\n",
    "            sign_flag = -1\n",
    "            s = s[1:]\n",
    "        else:\n",
    "            pass\n",
    "\n",
    "        for index in range(len(s)):\n",
    "            if ord(s[index]) <= ord(\"9\") and ord(s[index]) >= ord(\"0\"):\n",
    "                temp_int = int(s[index])\n",
    "                res = res*10 + temp_int\n",
    "            else:\n",
    "                break\n",
    "\n",
    "        res = res*sign_flag\n",
    "        return max(-2**31, min(2**31-1, res))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        s = s.lstrip(' ')\n",
    "        num = 0\n",
    "        sign = 1\n",
    "        hasNum = hasSign = False\n",
    "        for c in s:\n",
    "            if c in '+-' and not hasSign and not hasNum:\n",
    "                hasSign = True\n",
    "                if c == '-': sign = -1\n",
    "            elif c.isdigit():\n",
    "                hasNum = True\n",
    "                num = num * 10 + ord(c) - ord('0')\n",
    "                if sign < 0 and num > 1 << 31: return - (1 << 31)\n",
    "                if sign > 0 and num > (1 << 31) - 1: return (1 << 31) - 1\n",
    "            elif hasNum:\n",
    "                return sign * num\n",
    "            else:\n",
    "                return 0\n",
    "\n",
    "        return sign * num"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        s = str.strip()\n",
    "        result = 0\n",
    "        flag = -1 if (len(s) and s[0] == '-') else 1\n",
    "        if flag == -1 or (len(s) and s[0] == '+'):\n",
    "            s = s[1:]\n",
    "        i = 0\n",
    "        while i < len(s):\n",
    "            if s[i] in '0123456789':\n",
    "                i += 1\n",
    "            else:\n",
    "                break\n",
    "        s = s[:i]\n",
    "        for i, c in enumerate(s[::-1]):\n",
    "            result += int(c)*10**i\n",
    "        result *= flag\n",
    "        if result > 2147483647:\n",
    "            result = 2147483647\n",
    "        if result < -2**31:\n",
    "            result = -2**31\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        if not str:\n",
    "            return 0\n",
    "        int_max, int_min, bndry = 2**31 - 1, -2**31,  2**31//10\n",
    "        res, i,  length, sign = 0, 0, len(str), 1\n",
    "        while str[i] == ' ':\n",
    "            i += 1\n",
    "            if i == length:\n",
    "                return 0\n",
    "        if str[i] == '-':\n",
    "            sign = -1\n",
    "        if str[i] in '+-':\n",
    "            i += 1\n",
    "        for j in range(i, length):\n",
    "            if str[j] < '0' or str[j] > '9':\n",
    "                break\n",
    "            if res > bndry or res == bndry and str[j] > '7':\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = res * 10 + (ord(str[j]) - ord('0'))\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        res, i, sign, length = 0, 0, 1, len(str)\n",
    "        int_max, int_min, bound = 2**31 - 1, -2**31, 2**31 // 10\n",
    "        if not str: return 0\n",
    "        while str[i] == ' ':\n",
    "            i += 1\n",
    "            if i == length:\n",
    "                return 0\n",
    "        if str[i] == '-':\n",
    "            sign = -1\n",
    "        if str[i] in '+-':\n",
    "            i += 1\n",
    "        for j in range(i, length):\n",
    "            if not '0' <= str[j] <= '9':\n",
    "                break\n",
    "            if res > bound or (res == bound and str[j] > '7'):\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = 10 * res + ord(str[j]) - ord('0')\n",
    "        \n",
    "        return sign*res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str=str.strip()\n",
    "        if not str:\n",
    "            return 0\n",
    "        res,i,sign=0,1,1\n",
    "        int_max,int_min,boun=2**31-1,-2**31,2**31//10\n",
    "        if str[0]==\"-\":\n",
    "            sign=-1\n",
    "        elif str[0]!=\"+\":\n",
    "            i=0\n",
    "        for x in str[i:]:\n",
    "            if not \"0\"<=x<=\"9\":\n",
    "                break\n",
    "            if res > boun or res == boun and x > '7':\n",
    "                if sign==1:\n",
    "                    return int_max\n",
    "                else:\n",
    "                    return int_min\n",
    "            res=10*res+int(x)\n",
    "        return sign*res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        if not str:\n",
    "            return 0\n",
    "        int_max, int_min, bndry = 2**31 - 1, -2**31,  2**31//10\n",
    "        res, i,  length, sign = 0, 0, len(str), 1\n",
    "        while str[i] == ' ':\n",
    "            i += 1\n",
    "            if i == length:\n",
    "                return 0\n",
    "        if str[i] == '-':\n",
    "            sign = -1\n",
    "        if str[i] in '+-':\n",
    "            i += 1\n",
    "        for j in range(i, length):\n",
    "            if str[j] < '0' or str[j] > '9':\n",
    "                break\n",
    "            if res > bndry or res == bndry and str[j] > '7':\n",
    "                return int_max if sign == 1 else int_min\n",
    "            res = res * 10 + (ord(str[j]) - ord('0'))\n",
    "        return sign * res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import deque\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        if not str:\n",
    "            return 0\n",
    "        lenS, index, sign, res = len(str), 0, 1, 0\n",
    "        minValue, maxValue = -2**31, 2**31-1\n",
    "        while index < lenS and str[index] == ' ':\n",
    "            index += 1\n",
    "        if index < lenS and (str[index] == '+' or str[index] == '-'):\n",
    "            if str[index] == '-':\n",
    "                sign = -1\n",
    "            index += 1\n",
    "        while index < lenS:\n",
    "            if str[index] < '0' or str[index] > '9':\n",
    "                break\n",
    "            if res == 0 and str[index] == '0':\n",
    "                index += 1\n",
    "                continue\n",
    "            digit = int(str[index])\n",
    "            if res > (maxValue-digit)/10:\n",
    "                return maxValue if sign == 1 else minValue\n",
    "            res = res*10+digit\n",
    "            index += 1\n",
    "        return res*sign\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        str = str.strip()                      # 删除首尾空格\n",
    "        if not str: return 0                   # 字符串为空则直接返回\n",
    "        res, i, sign = 0, 1, 1\n",
    "        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10\n",
    "        if str[0] == '-': sign = -1            # 保存负号\n",
    "        elif str[0] != '+': i = 0              # 若无符号位，则需从 i = 0 开始数字拼接\n",
    "        for c in str[i:]:\n",
    "            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出\n",
    "            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理\n",
    "            res = 10 * res + ord(c) - ord('0') # 数字拼接\n",
    "        return sign * res\n",
    "\n",
    "         "
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
